//
//  HMUserAccountModel.swift
//  WeiBoXR
//
//  Created by acer on 16/9/22.
//  Copyright © 2016年 acer. All rights reserved.
//

import UIKit

var path = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("userAccount.archiver")
class HMUserAccountModel: NSObject ,NSCoding {

    //用户授权的唯一票据
    var access_token: String?
    //access_token的生命周期，单位是秒数。
    var expires_in: TimeInterval = 0 {
        
        didSet {
            expiresDate = Date().addingTimeInterval(expires_in)
        }
    }
    //  过期时间对象
    var expiresDate: Date?
    //    授权用户的UID
    var uid: Int64 = 0
    //  用户名
    var name: String?
    //  用户头像
    var profile_image_url: String?
    
    var avatar_large: String?
    
    

    init(dic: [String : Any]) {
        super.init()
        setValuesForKeys(dic)
    }
    
    
    //NSCoding
    func encode(with aCoder: NSCoder) {
        
        aCoder.encode(access_token, forKey: "access_token")
        aCoder.encode(expiresDate, forKey: "expiresDate")
        aCoder.encode(uid, forKey: "uid")
        aCoder.encode(name, forKey: "name")
        aCoder.encode(profile_image_url, forKey: "profile_image_url")
        aCoder.encode(avatar_large, forKey: "avatar_large")

    }
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
        uid = aDecoder.decodeInt64(forKey: "uid")
        name = aDecoder.decodeObject(forKey: "name") as? String
        profile_image_url = aDecoder.decodeObject(forKey: "profile_image_url") as? String
        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
    }
    override func setValue(_ value: Any?, forUndefinedKey key: String) {
        
    }
    
    func saveUserAccount () -> Void {
        
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    class func loadUserAccountModel () -> HMUserAccountModel? {
        
        return NSKeyedUnarchiver.unarchiveObject(withFile: path) as? HMUserAccountModel
    }
    
}
